import { nanoid } from 'nanoid'
import { Component } from 'react'
import PropTypes from 'prop-types'
import './index.css'

export default class Header extends Component {

  // 对 props 进行类型和必要性的检测
  static propTypes = {
    addTodo: PropTypes.func.isRequired
  }

  handleKeyUp = (event) => {
    const { target, keyCode } = event
    // enter 键
    if (keyCode !== 13) return;
    // 不能添加的为空
    if (target.value.trim() === '') {
      alert('不能为空')
      return
    }
    this.props.addTodo({ id: nanoid(), name: target.value, done: false })
    // 清空
    target.value = ''
  }

  render() {
    return (
      <div className="todo-header">
        <input onKeyUp={this.handleKeyUp} type="text" placeholder="请输入你的任务名称，按回车键确认"/>
      </div>
    )
  }
}
